/* eslint-disable */
// OCR任务的整体标注结果，用来从服务器获取数据并缓存下来
// 可以认为是浏览器端的数据层，前端直接通过操作数据层来获取和保存数据
import API from '@/js/api';
import LabelConfig from './LabelConfig';
import LabelStorageBase from './LabelStorageBase';
import { getFileBaseName } from '../utils/fileUtils';
import { createLabel } from '@/js/models/LabelBase.js';

// 本地LabelData的JS存储对象
class LabelStorageLocal extends LabelStorageBase {
    constructor() {
        super();
        this.per_page = 15;
        this.load_details = false;
    }

    // 从本地加载数据
    async loadDataset(dataset_info, load_config = {}) {
        // console.log('loadDataset dataset_info =', dataset_info);
        // 设置配置对象
        LabelConfig.setDatasetInfo(dataset_info);

        // 加载基础信息
        this.dataset_id = dataset_info.id;
        this.dataset_supertype = dataset_info.dataset_supertype;
        this.dataset_type = dataset_info.dataset_type;
        this.label_format = dataset_info.label_format;
        this.total_page = null;
        this.total_count = null;
        this.per_page = load_config.page_size ? load_config.page_size : 20;
        this.load_details = load_config.load_details ? load_config.load_details : false;

        // 加载categories信息
        this.categories = [];
        let result = await API.invoke('GetCategories', { dataset_id: this.dataset_id });
        if (result.code == 0) {
            this.parseCategories(result.msg);
        }
        // console.log(`loadDataset, categories = `, this.categories);

        // 加载分页列表数据
        let labeldatas = await this.getPageData(1);
        return {
            per_page: this.per_page,
            total_page: this.total_page,
            total_count: this.total_count,
            labeldatas: labeldatas
        };
    }

    // 解析原始返回的categories信息（对于coco数据集）
    parseCategories(categories) {
        this.categories = [];
        for (let i = 0; i < categories.length; i++) {
            let category = categories[i];
            if (category.keypoints) {
                category.keypoints = JSON.parse(category.keypoints);
            }
            if (category.skeleton) {
                category.skeleton = JSON.parse(category.skeleton);
            }
            this.categories.push(category);
        }
    }

    // 根据page_index获取对应一页的数据
    async getPageData(page_index) {
        // console.log('getPageData page_index = ', page_index);
        if (page_index < 1 || page_index > this.page_count) {
            return [];
        }

        let pairs = [];
        try {
            let result = await API.invoke('LoadDataset', { dataset_id: this.dataset_id, page: page_index, page_size: this.per_page, load_details: this.load_details });
            if (this.total_page === null || this.total_count === null) {
                this.total_page = result.msg.totalPages;
                this.total_count = result.msg.totalRecords;
            }
            this.current_page = page_index;
            pairs = result.msg.data;
        } catch (error) {
            console.error('LabelStorageLocal loadDataset Failed!, error = ', error);
            return [];
        }

        this.labeldatas = [];
        for (let i = 0; i < pairs.length; i++) {
            let data = {};

            data.pairs_id = pairs[i].pairs_id;
            data.image_url = pairs[i].image_path;
            data.label_url = pairs[i].label_path;
            data.create_time = pairs[i].create_time;
            data.update_time = pairs[i].update_time;
            data.name = getFileBaseName(data.image_url);
            data.autolabel_url = '';
            data.status = data.label_url ? 'Labeled' : 'NoLabeled';
            data.label_result = null;
            if (this.load_details) {
                data.image_info = pairs[i].image_info;
            }

            this.labeldatas.push(data);
        }

        // console.log('this.labeldatas = ', this.labeldatas);
        return this.labeldatas;
    }

    // 根据id获取对应的labeldata数据
    async getLabelData(index) {
        // console.log("getLabelData index = ", index);
        if (index < 0 || index >= this.labeldatas.length) {
            return {};
        }

        let labeldata = this.labeldatas[index];
        if (!labeldata.label_result) {
            // 加载对应的标注结果
            labeldata.label_result = await createLabel({ supertype: this.dataset_supertype, type: this.dataset_type }, this.label_format);
            let result = await API.invoke('LoadLabel', {
                dataset_id: this.dataset_id,
                dataset_supertype: this.dataset_supertype,
                dataset_type: this.dataset_type,
                label_format: this.label_format,
                image_path: labeldata.image_url,
                label_path: labeldata.label_url
            });
            if (result.code == 0) {
                labeldata.label_result.fromJson(result.msg);
            }
        }

        // console.log(this.labeldata[index]);
        return labeldata;
    }

    // 保存手工标注的结果
    async saveLabelData(index) {
        if (index < 0 || index >= this.labeldatas.length) {
            return false;
        }

        let labeldata = this.labeldatas[index];
        if (!labeldata.label_result) {
            console.log('labeldata.label_result is null');
            return false;
        }
        let params = {
            dataset_id: this.dataset_id,
            dataset_supertype: this.dataset_supertype,
            dataset_type: this.dataset_type,
            label_format: this.label_format,
            pairs_id: labeldata.pairs_id,
            image_url: labeldata.image_url,
            label_url: labeldata.label_url,
            labels: labeldata.label_result.labels
        };
        if (labeldata.label_result && !labeldata.label_result.saved) {
            // console.log(`saveLabelData params = `, params);
            let result = await API.invoke('SaveLabel', params);
            if (result.code == 0) {
                labeldata.label_result.saved = true;
            }
        }
    }

    // 删除某一条labeldata数据
    async deleteLabelData(index) {
        if (index < 0 || index >= this.labeldatas.length) {
            return false;
        }

        let label_data = this.labeldatas[index];
        let result = await API.invoke('DeleteFrames', {
            dataset_id: this.dataset_id,
            frames: JSON.stringify([label_data.pairs_id])
        });
        // console.log(result);
        return result;
    }
}

export default new LabelStorageLocal();
